﻿Imports System.Linq
Imports SISSAT.BusinessLayer.Managers
Imports SISSAT.BusinessLayer.DomainModels
Imports SISSAT.BusinessLayer.Services

Namespace Views
    Public Class GradeListControlPresenter

        Private Property View As IGradeListControlView
        Private Property ExaminationService As IExaminationService
        Private Property TypeService As IExaminationTypeService
        Private Property EmployeeService As IEmployeeService
        Private Property Manager As GradePointManager

        Public Sub New(view As IGradeListControlView)
            Me.View = view

            ExaminationService = New ExaminationService
            TypeService = New ExaminationTypeService
            EmployeeService = New EmployeeService
            Manager = New GradePointManager(Me.View.CurrentUserId)

            AddHandler Me.View.OnInitialization, AddressOf OnInitialization
            AddHandler Me.View.OnSelectedIndexChange, AddressOf OnSelectedIndexChange
            AddHandler Me.View.OnSubmit, AddressOf OnSubmit
        End Sub

        Private Sub OnInitialization()
            Dim examinationTypes As IEnumerable(Of ExaminationType) = TypeService.ReadAll(0) ' 0 = Preliminary, Midterms, Prefinals & Finals

            Me.View.DropDownListDataSource = From type In examinationTypes
                                             Let id As String = Convert.ToString(type.ExaminationTypeId)
                                             Let text As String = String.Format("{0} Examination", type.Name)
                                             Select New KeyValuePair(Of String, String)(id, text)
            Me.View.RepeaterDataSource = TypeService.ReadAll(-1)
        End Sub

        Private Sub OnSelectedIndexChange()
            Dim entities As IEnumerable(Of Examination) = _
                ExaminationService.ReadAll(Me.View.EmployeeCode, Me.View.ScheduleId, Me.View.SelectedValue)

            Me.View.RepeaterData = entities
        End Sub

        Private Sub OnSubmit(createItems As DataTable, updateItems As DataTable)
            Dim count As Integer = createItems.Rows.Count() + updateItems.Rows.Count()

            ExaminationService.Create(createItems, Me.View.CurrentUserId)
            ExaminationService.Edit(updateItems, Me.View.CurrentUserId)

            If (count > 0) Then
                Manager.ComputeGrade(Me.View.EmployeeCode, Me.View.ScheduleId, Me.View.SelectedValue)
            Else
                Me.View.ErrorMessage = "No changes were detected. Save aborted."
            End If
        End Sub

    End Class
End Namespace

